<?php
namespace common\components;

use Yii;
use yii\base\Event;
use yii\base\Component;
use yii\web\HttpException;

use common\components\SmInterface;
use yii\base\Object;

class SmChuanglan extends Component implements SmInterface
{
    public $username;

    public $password;

    public $api_send_url = 'http://222.73.117.158/msg/HttpBatchSendSM';

    public $api_balance_query_url = 'http://222.73.117.158/msg/QueryBalance';

    public function send($mobiles, $content)
    {
        $mobiles = is_string($mobiles) ? $mobiles : implode(',', $mobiles);    
        $result = $this->sendSMS($mobiles, $content, 'true');
        $result = $this->execResult($result);
        if($result[1] == 0){
            return (Object)['SendSmsTradeResult'=>1];
            //echo '发送成功';
        } else{
            yii::error("发送失败{$result[1]}");
            throw new \Exception("发送失败{$result[1]}", 1);
        }
    }

    public function getBalance()
    {
        $result = $this->queryBalance();
        $result = $this->execResult($result);
        switch($result[1]){
            case 0:
                //echo "剩余{$result[3]}条";
                return $result[3];
                break;
            case 101:
                yii::error('无此用户');
                break;
            case 102:
                yii::error('密码错');
                break;
            case 103:
                yii::error('查询过快');
                break;
        }
        throw new \Exception("查询失败{$result[1]}", 1);
    }

	protected function sendSMS( $mobile, $msg, $needstatus = 'false', $product = '', $extno = '') {
		$postArr = array (
				          'account' => $this->username,
				          'pswd' => $this->password,
				          'msg' => $msg,
				          'mobile' => $mobile,
				          'needstatus' => $needstatus,
				          'product' => $product,
				          'extno' => $extno
                     );
		
		$result = $this->curlPost($this->api_send_url, $postArr);
		return $result;
	}
	
	protected function queryBalance() {
		$postArr = array ( 
		          'account' => $this->username,
		          'pswd' => $this->password,
		);
		$result = $this->curlPost($this->api_balance_query_url, $postArr);
		return $result;
	}

	protected function execResult($result){
		$result=preg_split("/[,\r\n]/",$result);
		return $result;
	}

	private function curlPost($url,$postFields){
		$postFields = http_build_query($postFields);
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postFields );
		$result = curl_exec ( $ch );
		curl_close ( $ch );
		return $result;
	}

}

